import { _decorator, Component, EventTouch, Input, Label, Node, UITransform, Vec3 } from 'cc';
import { BezierCurveTool } from './BezierCurveTool';
import EventMgr from './EventManager';
import { EventType } from './enumType';
const { ccclass, property } = _decorator;

@ccclass('paragraph')
export class paragraph extends Component {
    public labelStr: string = "0";
    startPos: Vec3 = new Vec3(0, 0, 0);
    snap: Node = null;
    start() {
        this.setupNodeDragging();
    }

    setupNodeDragging() {
        this.node.children.forEach((child, index) => {
            child.on(Input.EventType.TOUCH_MOVE, this.onNodeTouchMove, this);
            child.children[0].getComponent(Label).string = this.labelStr;
            child.setPosition(this.startPos.x + index * 100, this.startPos.y);
            if (index === 0) {
                child.on(Input.EventType.TOUCH_END, this.onNodeTouchEnd, this);
            } else if (index === 2) {
                child.on(Input.EventType.TOUCH_END, this.onNodeTouchEnd, this);
            }
        });
    }

    onNodeTouchMove(event: EventTouch) {
        const target = event.target as Node;
        const pos_ = event.getUILocation();
        const pos = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(pos_.x, pos_.y, 0));
        target.setPosition(pos.x, pos.y);
        this.snap = target;
        EventMgr.Instance.emit(EventType.drawBezierCurves);
    }

    onNodeTouchEnd() {
        const bezierCurveTool = this.node.parent?.getComponent(BezierCurveTool);
        if (bezierCurveTool) {
            bezierCurveTool.checkSnap(this.snap);
            bezierCurveTool.drawBezierCurves();
        }
        EventMgr.Instance.emit(EventType.drawBezierCurves);
    }
}